package org.dromara.common.mp.utils;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.mp.entity.WxMpTemplateMessageResult;

/**
 * 微信公众号工具类
 * @author denny
 */
@Slf4j
public class WxMpUtils {
    /**
     * 微信公众号服务service
     */
    public static final WxMpService WX_MP_SERVICE = SpringUtils.getBean(WxMpService.class);

    /**
     * 发送模板消息
     * @param templateMessage 模板消息
     * @return 发送结果
     */
    public static WxMpTemplateMessageResult sendTemplateMessage(WxMpTemplateMessage templateMessage) {
        WxMpTemplateMessageResult result = new WxMpTemplateMessageResult();
        if (templateMessage == null) {
            log.error("发送模板消息失败：模板消息为空");
            result.setResult(false);
            result.setErrorMsg("模板消息为空");
            return result;
        }
        if (templateMessage.getToUser() == null) {
            log.error("发送模板消息失败：接收者OpenID为空");
            result.setResult(false);
            result.setErrorMsg("接收者OpenID为空");
            return result;
        }
        if (templateMessage.getTemplateId() == null) {
            log.error("送模板消息失败：模板ID为空");
            result.setResult(false);
            result.setErrorMsg("模板ID为空");
            return result;
        }
        if (CollectionUtil.isEmpty(templateMessage.getData())) {
            log.error("发送模板消息失败：消息数据为空");
            result.setResult(false);
            result.setErrorMsg("消息数据为空");
            return result;
        }
        try {
            String msgId  = WX_MP_SERVICE.getTemplateMsgService().sendTemplateMsg(templateMessage);
            result.setResult(true);
            result.setMsgId(msgId);
            log.info("发送模板消息成功：{}", msgId);
            return result;
        } catch (WxErrorException e) {
            log.error("发送模板消息失败：{}", e.getMessage());
            result.setResult(false);
            result.setErrorMsg(e.getMessage());
            return result;
        }
    }
}
